package com.cashmama.market.api.infras.utils;

import com.cashmama.market.api.infras.exception.BizException;
import org.springframework.util.Base64Utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * @ClassName MoheAESUtil
 * @Description 魔盒aes加解密方法
 * @Author fengkai
 * @Date 2019-07-10 15:45
 * @ModifyDate 2019-07-10 15:45
 */
public class MoheAESUtil {

    // 密钥算法
    public static final String KEY_ALGORITHM = "AES";
    // 加密/解密算法/工作模式/填充方式
    public static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
    private final static String FIX_KEY = "TONGDUNSHUJUMOHE";

    /**
     * 加密
     *
     * @param source
     * @param key
     * @return
     */
    public static String encrypt(String source, String key) {
        try {
            String cryptKey = getCryptKey(key);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(cryptKey.getBytes(), KEY_ALGORITHM));
            byte[] secret = cipher.doFinal(source.getBytes());
            return Base64Utils.encodeToString(secret);
        } catch (Exception e) {
            throw new BizException("failed@AesCoder.encrypt", e);
        }
    }

    /**
     * 解密
     * @param encoded
     * @param key
     * @return
     */
    public static String decrypt(String encoded, String key) {
        try {
            String cryptKey = getCryptKey(key);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(cryptKey.getBytes(), KEY_ALGORITHM));
            byte[] secret = Base64Utils.decodeFromString(encoded);
            return new String(cipher.doFinal(secret));
        } catch (Exception e) {
            throw new BizException("failed@AesCoder.decrypt", e);
        }
    }

    private static String getCryptKey(String key) {
        if (null == key) {
            key = FIX_KEY;
        } else {
            key = key + FIX_KEY;
        }
        char[] chars = key.toCharArray();
        StringBuilder keys = new StringBuilder();
        for (int i = 0; i < chars.length; i += 3) {
            keys.append(chars[i]);
        }
        int length = keys.length();
        if (length == 16) {
            return keys.toString();
        } else if (length > 16) {
            return keys.substring(0, 16);
        } else {
            for (int i = 0; i < 16 - length; i++) {
                keys.append("0");
            }
            return keys.toString();
        }
    }

}
